package com.hightrast.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.hightrast.service.api.domain.qo.rastOrderItem.QueryOrderProductItemsQo;
import com.hightrast.service.api.domain.qo.rastOrderItem.UpdateOrderProductItemsPaybackStatusQo;
import com.hightrast.service.api.domain.vo.rastOrderItem.QueryOrderProductItemsVo;
import com.hightrast.service.api.entity.*;
import com.hightrast.service.api.enums.OrderStatusEnum;
import com.hightrast.service.api.enums.PaybackStatusEnum;
import com.hightrast.service.api.enums.RefundStatusEnum;
import com.hightrast.service.api.enums.RoleTypeEnum;
import com.hightrast.service.compareToData.EntitySynchronizer;
import com.hightrast.service.compareToData.stage.impl.RastOrderProductItemComparator;
import com.hightrast.service.compareToData.stage.impl.RastOrderProductItemRefundComparator;
import com.hightrast.service.compareToData.stage.impl.RastOrderProductItemRefundUpdater;
import com.hightrast.service.compareToData.stage.impl.RastOrderProductItemUpdater;
import com.hightrast.service.mapper.RastOrderProductItemsMapper;
import com.hightrast.service.service.*;
import com.hightrast.service.util.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单商品项表 服务实现类
 * </p>
 *
 * @author hx
 * @since 2025-01-24
 */
@Service
@Slf4j
public class RastOrderProductItemsServiceImpl extends ServiceImpl<RastOrderProductItemsMapper, RastOrderProductItems> implements IRastOrderProductItemsService {

    @Resource
    IRastProductsService productsService;
    @Resource
    IRastUserRoleService userRoleService;
    @Resource
    IRastUserVendorService userVendorService;
    @Resource
    IRastOrderProductRefundItemsService refundItemsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrderProductItems(List<RastOrderProductItems> orderProductItems, List<RastOrderProductRefundItems> refundItems) {
        if(CollectionUtil.isEmpty(orderProductItems)){
            log.info("商品项数据为空");
            return;
        }

        // 获取商品的佣金率
        List<Long> productIds = orderProductItems.stream().map(RastOrderProductItems::getProductId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<Long, RastProducts> productsMap = productsService.list(new LambdaQueryWrapper<RastProducts>().in(RastProducts::getId, productIds)).stream().collect(Collectors.toMap(RastProducts::getId, Function.identity(), (v1, v2) -> v2));
        // 订单退款项
        Map<Long, List<RastOrderProductRefundItems>> refundItemMap = refundItems.stream().collect(Collectors.groupingBy(RastOrderProductRefundItems::getLineItemId));

        List<RastOrderProductItems> newOrderProductItems = new ArrayList<>(); // 获取到的shopify数据和退款的新增数据

        for (RastOrderProductItems productItem : orderProductItems) {
            // 通用设置佣金
            Optional.ofNullable(productsMap.get(productItem.getProductId())).ifPresent(prd -> {
                productItem.setCommissonRate(prd.getCommissonRate());
            });
            RastOrderProductItems rtItem = BeanUtil.copyProperties(productItem, RastOrderProductItems.class);
            // 默认状态
            rtItem.setPaybackStatus(PaybackStatusEnum.Issuing.getValue());
            rtItem.setOrderStatus(OrderStatusEnum.In_Transit.getValue());
            if(Objects.equals(rtItem.getFulfillmentStatus(),"fulfilled")){
                rtItem.setOrderStatus(OrderStatusEnum.Goods_Received.getValue());
            }
            // 如果存在退款的商品项那么再新增一条同样的商品项数据，只是这条数据的 最终价格 和 数量  是退款的金额 和 退款的数量
            List<RastOrderProductRefundItems> lineRefundItems = refundItemMap.getOrDefault(productItem.getId(), Lists.newArrayList());
            lineRefundItems.stream().findFirst().ifPresent(irf -> {
                if(RefundStatusEnum.success.getDesc().equals(irf.getStatus())){
                    rtItem.setOrderStatus(OrderStatusEnum.Return_Goods.getValue());
                    rtItem.setPaybackStatus(PaybackStatusEnum.Not_issued.getValue());
                }
            });
            for (RastOrderProductRefundItems lineRefundItem : lineRefundItems) {
                RastOrderProductItems rastOrderProductItems = BeanUtil.copyProperties(productItem, RastOrderProductItems.class);
                // 退款的商品项id为退款记录中的id
                rastOrderProductItems.setId(lineRefundItem.getId());
                rastOrderProductItems.setPreTaxPrice(lineRefundItem.getSubtotal());
                rastOrderProductItems.setQuantity(lineRefundItem.getQuantity());
                rastOrderProductItems.setPrimaryItemId(lineRefundItem.getLineItemId());
                rastOrderProductItems.setPaybackStatus(PaybackStatusEnum.Not_issued.getValue());
                rastOrderProductItems.setOrderStatus(OrderStatusEnum.Return_Goods.getValue());
                if(RefundStatusEnum.success.getDesc().equals(lineRefundItem.getStatus())){
                    rastOrderProductItems.setOrderStatus(OrderStatusEnum.Return_Goods.getValue());
                }
                newOrderProductItems.add(rastOrderProductItems);
            }
            newOrderProductItems.add(rtItem);
        }
        // 获取原订单商品项数据
        List<RastOrderProductItems> oldProductItems = this.list();
        Map<Long, RastOrderProductItems> oldProductItemsMap = oldProductItems.stream().collect(Collectors.toMap(RastOrderProductItems::getId, Function.identity(), (v1, v2) -> v2));
        Consumer<List<Long>> deleteFunction = ids -> {
            // 实现商品项删除逻辑
            List<Long> deleIds = ids.stream().distinct().filter(dlItem -> {
                RastOrderProductItems delProductItem = oldProductItemsMap.get(dlItem);
                // 退款商品项目 暂时不删除
                if (Objects.nonNull(delProductItem)
                        && Objects.nonNull(delProductItem.getPrimaryItemId())
                        && delProductItem.getPrimaryItemId() != 0) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(deleIds)){
                this.removeByIds(deleIds);
            }
        };

        Consumer<List<RastOrderProductItems>> saveBathFunction = addItems -> {
            List<String> vendors = addItems.stream().map(RastOrderProductItems::getVendor).distinct().collect(Collectors.toList());
            Map<String, Long> userVendorMap = userVendorService.queryUserVendors(vendors).stream().collect(Collectors.toMap(RastUserVendor::getVendor, RastUserVendor::getUserId, (v1, v2) -> v2));
            // 实现商品项新增逻辑
            List<RastOrderProductItems> saveItems = addItems.stream().distinct().peek(addItem -> {
                // 设置当前商品项所属设计师
                if(StrUtil.isNotEmpty(addItem.getVendor())){
                    Optional.ofNullable(userVendorMap.get(addItem.getVendor())).ifPresent(addItem::setUserId);
                }
            }).collect(Collectors.toList());
            this.saveBatch(saveItems);
        };
        //对比数据更新订单
        EntitySynchronizer.syncEntities(newOrderProductItems,
                oldProductItems,
                RastOrderProductItems::getId,
                this::updateBatchById,
                saveBathFunction,
                deleteFunction,
                new RastOrderProductItemComparator(),
                new RastOrderProductItemUpdater());

        //对比数据退款项数据 不暂时不做删除操作
        List<RastOrderProductRefundItems> oldRefundItems = refundItemsService.list();
        EntitySynchronizer.syncEntities(refundItems,
                oldRefundItems,
                RastOrderProductRefundItems::getId,
                refundItemsService::updateBatchById,
                refundItemsService::saveBatch,
                null,
                new RastOrderProductItemRefundComparator(),
                new RastOrderProductItemRefundUpdater());


    }

    /**
     * 获取商品订单列表
     */
    @Override
    public IPage<QueryOrderProductItemsVo> queryOrderProductItems(QueryOrderProductItemsQo qo){
        RastUser user = SecureUtil.getUser();
        IPage<QueryOrderProductItemsVo> page = new Page<>(qo.getPage(), qo.getPageSize());
        // 是否存在管理者角色
        RastUserRole rastUserRole = userRoleService.queryUserRoleByUserId(user.getId()).stream().filter(a -> a.getRoleType().equals(RoleTypeEnum.ADMIN.getValue())).findFirst().orElse(null);

        if(Objects.isNull(rastUserRole)){
            qo.setUserId(user.getId());
            // 非管理者 获取当前用户绑定的品牌
//            RastUserVendor userVendor = userVendorService.getOne(new LambdaQueryWrapper<RastUserVendor>().eq(RastUserVendor::getUserId, user.getId()));
//            if(Objects.nonNull(userVendor) && StringUtils.isNotEmpty(userVendor.getVendor())){
//                qo.setVendor(userVendor.getVendor());
//            }else {
//                return page;
//            }
        }

        // 获取商品订单列表
        IPage<QueryOrderProductItemsVo> orderProductItems = this.baseMapper.selectOrderProductItems(page,qo);

        if(CollectionUtil.isNotEmpty(orderProductItems.getRecords())){
            orderProductItems.getRecords().forEach(recorde ->{
                OrderStatusEnum orderStatusEnum = OrderStatusEnum.getItem(recorde.getOrderStatus());
                recorde.setOrderStatusStr(orderStatusEnum != null ? orderStatusEnum.getDesc() : StringUtils.EMPTY);
                PaybackStatusEnum paybackStatusEnum = PaybackStatusEnum.getItem(recorde.getPaybackStatus());
                recorde.setPaybackStatusStr(paybackStatusEnum != null ? paybackStatusEnum.getDesc() : StringUtils.EMPTY);
            });
//            if(Objects.nonNull(rastUserRole)){
//                log.info("进入管理者组装人");
//                List<String> vendors = orderProductItems.getRecords().stream().map(QueryOrderProductItemsVo::getVendor).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
//
//                // 获取这些品牌关联的人
//                Map<String, String> userVendorMap = userVendorService.queryUserVendors(vendors).stream().collect(Collectors.toMap(RastUserVendor::getVendor, RastUserVendor::getUserName, (v1, v2) -> v1));
//
//                orderProductItems.getRecords().forEach(product -> {
//                    Optional.ofNullable(userVendorMap.get(product.getVendor()))
//                            .ifPresent(product::setDesigner);
//                });
//
//            }else {
//                log.info("进入非管理者组装人");
//                orderProductItems.getRecords().forEach(product -> product.setDesigner(user.getUserName()));
//            }
        }
        return orderProductItems;
    }

    @Override
    public void updateOrderProductItemsPaybackStatus(UpdateOrderProductItemsPaybackStatusQo qo){

        // 只有管理员才能修改
        this.update(new LambdaUpdateWrapper<RastOrderProductItems>()
                .set(RastOrderProductItems::getPaybackStatus,qo.getPaybackStatus())
                .eq(RastOrderProductItems::getId,qo.getId()));

    }

}
